package handlers

import (
	"go-ddd-ecommerce/internal/application/dto"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"

	"go-ddd-ecommerce/internal/application/services"
)

type UserController struct {
	userService *services.UserAppService
}

func NewUserController(userService *services.UserAppService) *UserController {
	return &UserController{userService: userService}
}

type CreateUserRequest struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

type UpdatePasswordRequest struct {
	UserID      string `json:"user_id" binding:"required"`
	NewPassword string `json:"new_password" binding:"required"`
}

type GetUserByIdRequest struct {
	UserID string `json:"user_id" binding:"required"`
}

type AddBalanceRequest struct {
	UserID  string  `json:"user_id" binding:"required"`
	Balance float64 `json:"balance" binding:"required"`
}

// 创建用户
func (uc *UserController) CreateUser(c *gin.Context) {
	var req CreateUserRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	cmd := dto.CreateUserDTO{
		Username: req.Username,
		Password: req.Password,
	}
	user, err := uc.userService.CreateUser(cmd)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, gin.H{
		"message": "用户创建成功",
		"user":    user,
	})
}

// 更新密码
func (uc *UserController) UpdatePassword(c *gin.Context) {

	var req UpdatePasswordRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	cmd := dto.UpdateUserPasswordDTO{
		UserID:      uuid.MustParse(req.UserID),
		NewPassword: req.NewPassword,
	}
	if err := uc.userService.UpdateUserPassword(cmd); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "密码修改成功"})
}

// 获取用户信息
func (uc *UserController) GetUser(c *gin.Context) {
	var req GetUserByIdRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	cmd := dto.GetUserByIDDTO{
		UserID: uuid.MustParse(req.UserID),
	}

	user, err := uc.userService.GetUserByID(cmd)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "没有找到用户"})
		return
	}

	c.JSON(http.StatusOK, user)
}

// 添加余额
func (uc *UserController) AddBalance(c *gin.Context) {
	var req AddBalanceRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	cmd := dto.AddUserBalanceDTO{
		UserID: uuid.MustParse(req.UserID),
		Amount: req.Balance,
	}
	if err := uc.userService.AddUserBalance(cmd); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "增加余额成功"})
}
